<template>
  <div class="bar">
    <div class="bar-legend">
      <div class="legend legend--on">
        <div class="marker"></div>
        <div class="text">
          {{ $t('periodStatusMonitoring.table.online') }}: {{ result.online }}%
        </div>
      </div>
      <div class="legend">
        <div class="marker"></div>
        <div class="text">
          {{ $t('periodStatusMonitoring.table.offline') }}: {{ result.offline }}%
        </div>
      </div>
    </div>
    <div class="bar-progress">
      <n-popover
        v-for="(item, index) in padValue"
        ref="popover"
        placement="top"
        content-class="progress-popover"
        trigger="hover"
        :key="index"
      >
        <div class="progress-popover__wrapper">
          <div>
            {{ $t('periodStatusMonitoring.table.machineStatus') }}:&nbsp;
            <span class="color--on">{{ $t(`periodStatusMonitoring.table.${item.type}`) }}</span>
          </div>
          <div>
            {{ $t('periodStatusMonitoring.table.startTime') }}:&nbsp;
            <span class="color">{{ item.startTime }}</span>
          </div>
          <div>
            {{ $t('periodStatusMonitoring.table.endTime') }}:&nbsp;
            <span class="color">{{ item.endTime }}</span>
          </div>
          <div>
            {{ $t('periodStatusMonitoring.table.duration') }}:&nbsp;
            <span class="color">{{ item.duration }}</span>
          </div>
        </div>
        <template #trigger>
          <div
            :style="{
              left: `${item.startPercent}%`,
              width: `${item.rang}%`,
            }"
            :class="['slider', { 'slider--on': item.type === 'online' }]"
          ></div>
        </template>
      </n-popover>
    </div>
    <div class="bar-tick">
      <div class="axis flex">
        <div class="tick" v-for="i in 25" :key="`tick-${i}`">
          <div class="line"></div>
          <div class="label">{{ getTick(i) }}</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup name="ProgressBar">
  import dayjs from 'dayjs';
  import { parseTime } from '@/utils/dateUtil';
  import { useMixins } from '@/hooks/useMixins';

  const { t } = useMixins();

  type Props = {
    value: any;
    today: any;
  };

  const props = withDefaults(defineProps<Props>(), {
    value: () => null,
    today: Boolean,
  });

  function parseProgress(times) {
    const [start, end] = times.map((item) => calcPercentage(item));
    const range = end - start;
    return {
      start,
      range,
      fixed: range.toFixed(2),
    };
  }
  //
  const TOTAL_LENGTH = 24 * 60 * 60 - 1;

  function calcPercentage(time) {
    const [h = 0, m = 0, s = 0] = time.split(':').map((t) => parseInt(t));
    const second = h * 60 * 60 + m * 60 + s;
    return (second * 100) / TOTAL_LENGTH;
  }
  function getDuration(start, end, { hStr, mStr }) {
    const day = dayjs(`2022-01-01 ${end}`);
    const total = day.diff(`2022-01-01 ${start}`, 'm');
    const h = parseInt((total / 60) as any);
    const m = parseInt((total % 60) as any);
    return `${h}${hStr}${m}${mStr}`;
  }

  // const nowTime = new Date();

  const getTick = (num) => {
    num = num - 1;
    if (num % 2) return '';
    num = ('' + num).padStart(2, '00');
    return `${num}:00`;
  };

  const percentValue = computed(() => {
    return props.value.map((arr) => {
      const [startTime, endTime] = arr;
      return {
        startTime,
        startPercent: calcPercentage(startTime),
        endTime,
        endPercent: calcPercentage(endTime),
      };
    });
  });

  const padValue = computed(() => {
    const hStr = t('periodStatusMonitoring.table.h');
    const mStr = t('periodStatusMonitoring.table.m');

    const pad = percentValue.value.reduce((previous, current, _i) => {
      const { startTime, startPercent } = current;
      const { endTime = '00:00', endPercent = 0 } = previous.at(-1) || {};
      return [
        ...previous,
        {
          startTime: endTime,
          startPercent: endPercent,
          endTime: startTime,
          endPercent: startPercent,
          type: 'offline',
          rang: startPercent - endPercent,
          duration: getDuration(endTime, startTime, { hStr, mStr }),
        },
        {
          ...current,
          type: 'online',
          rang: current.endPercent - startPercent,
          duration: getDuration(startTime, current.endTime, { hStr, mStr }),
        },
      ];
    }, []);
    // 补齐最后结束时间
    const last = pad.at(-1) || {};

    if (last.endPercent !== 100) {
      // 非当天结束时间 23：59
      const lastEndTime = last.endTime ?? '00:00';
      const lastEndPercent = last.endPercent ?? 0;
      const item = {
        type: 'offline',
        startTime: lastEndTime,
        startPercent: lastEndPercent,
        endTime: '23:59',
        endPercent: 100,
        rang: 100 - lastEndPercent,
        duration: getDuration(lastEndTime, '23:59', {
          hStr,
          mStr,
        }),
      };
      // 当天结束时间 单钱时间
      if (props.today) {
        const nowDate = parseTime(new Date(), '{h}:{i}');
        item.endTime = nowDate;
        item.endPercent = calcPercentage(nowDate);
        item.rang = item.endPercent - item.startPercent;
        item.duration = getDuration(item.startTime, nowDate, { hStr, mStr });
      }

      pad.push(item);
    }

    return pad;
  });

  const result = computed(() => {
    const online = props.value.reduce((previous, current) => {
      const { fixed } = parseProgress(current);

      return previous + parseFloat(fixed);
    }, 0);

    if (props.today) {
      const now = new Date(); // 当前时间

      const startOfDay = new Date(
        `${now.getFullYear()}-${now.getMonth() + 1}-${now.getDate()} 00:00:00`
      ).getTime(); // 今天的开始时间（00:00:00）

      const bi = (now.getTime() - startOfDay) / 1000 / TOTAL_LENGTH; // 当前时间占一天的比例

      // const online2 = (online * bi).toFixed(2);

      // const offline = (100 - Number(online2) - (1 - bi) * 100).toFixed(2);

      const offline = (100 * bi - online).toFixed(2);

      return { online: online.toFixed(2), offline };

      // return { online: online2, offline };
    } else {
      const offline = (100 - online).toFixed(2);

      return { online: online.toFixed(2), offline };
    }
  });
</script>
<style lang="less" scoped>
  .bar {
    .flex {
      display: flex;
      align-items: center;
      justify-content: space-between;
    }
  }
  .bar-legend {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 40px;
    .legend {
      display: flex;
      align-items: center;
      margin-right: 30px;
      &--on.legend {
        .marker {
          background-color: #52c570;
        }
      }
      .marker {
        width: 24px;
        height: 12px;
        margin-right: 8px;
        border-radius: 2px;
        background-color: #e1e1e1;
      }
      .text {
        font-size: 12px;
        color: #666;
      }
    }
  }
  .bar-progress {
    position: relative;
    height: 20px;
    text-align: center;
    // background-color: #fafafa;
    .slider {
      position: absolute;
      left: 0;
      top: 0;
      height: 100%;
      font-size: 12px;
      background-color: #e1e1e1;
      cursor: pointer;
      .slider-text {
        line-height: 20px;
        font-size: 12px;
        color: #fff;
        visibility: hidden;
      }
      &:hover {
        .slider-text {
          visibility: visible;
        }
      }
      &--none {
        background: #fafafa;
      }
      &--on {
        background-color: #52c570;
      }
    }
  }
  .bar-tick {
    width: 100%;
    .axis {
      border-top: 1px solid #e6e6e6;
      .tick {
        width: 0;
        height: 36px;
        .line {
          font-size: 0;
          width: 1px;
          height: 6px;
          background-color: #e6e6e6;
        }
        .label {
          margin-top: 16px;
          font-size: 14px;
          color: #999999;
          line-height: 14px;
          transform: translateX(-16px);
          word-break: normal;
        }
      }
    }
  }
</style>

<style lang="less">
  .progress-popover {
    &__wrapper {
      display: flex;
      flex-direction: column;
      font-size: 12px;
      line-height: 24px;
      color: #999;
      .color--on {
        color: #52c570;
      }
      .color {
        color: #666;
      }
    }
  }
</style>
